package me.huanmeng.heater.impl;

import cn.hutool.http.HttpRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import me.huanmeng.heater.bot.Bot;
import me.huanmeng.heater.bot.MessageHelper;
import me.huanmeng.heater.exception.BotException;
import me.huanmeng.heater.http.KaiheilaApi;
import me.huanmeng.heater.socket.BotSocketClient;
import org.java_websocket.framing.CloseFrame;
import org.json.JSONObject;

import java.net.URI;
import java.util.UUID;

/**
 * 2021/9/26<br>
 * Heater<br>
 * WebSocket类型
 *
 * @author huanmeng_qwq
 */
public class BotSocketMain implements Bot, MessageHelper {
    private boolean login;
    private BotSocketClient botSocketClient;
    @Setter
    @Getter
    private int sn;
    @Setter
    @Getter
    private UUID session_id;
    private final KaiheilaApi kaiheilaApi;

    @SneakyThrows
    public BotSocketMain(KaiheilaApi kaiheilaApi) {
        this.kaiheilaApi = kaiheilaApi;
    }
    @Override
    public void login() throws Exception {
        final HttpRequest req = kaiheilaApi.doGet("/gateway/index").form("compress", 0);
        final String response = req.executeAsync().body();
        final JSONObject resp = new JSONObject(response);
        if(session_id !=null){
            debug("reconnect session: "+session_id);
            resp.put("session_id", session_id.toString());
            resp.put("sn",sn);
        }
        final int code = resp.getInt("code");
        if (code != 0) {
            throw new BotException(String.format("Gateway error code %s,response: %s", code, response));
        }
        setSn(0);
        final URI wssUrl = getWssUrl(resp);
        if (botSocketClient != null && botSocketClient.isOpen()) {
            botSocketClient.close();
        }
        botSocketClient = new BotSocketClient(this, wssUrl);
        debug("Connect to " + wssUrl);
        botSocketClient.connect();
        login = true;
    }

    private URI getWssUrl(JSONObject jsonObject) {
        final StringBuilder sb = new StringBuilder(jsonObject.getJSONObject("data").getString("url"));
        if(jsonObject.has("sn")&&jsonObject.has("session_id")){
            sb.append("&sn=").append(jsonObject.get("sn")).append("&session_id=").append(jsonObject.get("session_id"))
                    .append("&resume=1");
        }
        return URI.create(sb.toString());
    }

    @Override
    public boolean isLoggedIn() {
        return login;
    }

    @Override
    public void logout() {
        if (botSocketClient != null && botSocketClient.isOpen()) {
            botSocketClient.close(CloseFrame.NORMAL, "logout");
        }
        login = false;
    }
}
